#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <semaphore.h>

pthread_mutex_t mylock;
pthread_cond_t mycond;

int num[] = {1, 2, 3, 4, 5};

void *fun1(void *arg) {
    int i;
    
    pthread_mutex_lock(&mylock);    //上锁
    for(i = 0; i < 5; i++) {
        printf("thread1:%d\n", num[i]);
        sleep(1);
    }
    pthread_mutex_unlock(&mylock);  //解锁
    pthread_cond_signal(&mycond);   //发送条件变量的唤醒信号，发送信号有时间消耗，需要等信号发送完才可以退出
    sleep(1);                       //
    pthread_exit(NULL);
}

void *fun2(void *arg) {
    int i;

    pthread_mutex_lock(&mylock);            //上锁
    pthread_cond_wait(&mycond, &mylock);    //等待条件变量的唤醒信号
    for(i = 4; i >= 0; i--) {
        printf("thread2:%d\n", num[i]);
        sleep(1);
    }
    pthread_mutex_unlock(&mylock);          //解锁
    pthread_exit(NULL);
    return 0;
}

int main(int argc, const char *argv[]) {
    pthread_t thread1, thread2;

    if(pthread_create(&thread1, NULL, fun1, NULL) != 0) {
        perror("pthread_create thread1");
        _exit(1);
    }
    if(pthread_create(&thread2, NULL, fun2, NULL) != 0) {
        perror("pthread_create thread2");
        _exit(1);
    }
    if(pthread_mutex_init(&mylock, NULL) != 0) {
        perror("pthread_mutex_init");
        _exit(1);
    }
    if(pthread_cond_init(&mycond, NULL) != 0) {
        perror("pthread_cond_init");
        _exit(1);
    }

    pthread_join(thread1, NULL);
    pthread_join(thread2, NULL);

    return 0;
}

